//
//  RCTVoiceAssistant.m
//  VoiceAssistant
//
//  Created by G on 2020/2/17.
//  Copyright © 2020年 G. All rights reserved.
//

#import "RCTVoiceAssistant.h"

NSString *const kEmitResponse = @"VoiceAssistant_Resp";
static BOOL kShouldFinish = NO;

@implementation RCTVoiceAssistant


- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

+ (BOOL)requiresMainQueueSetup
{
    return YES;
}

RCT_EXPORT_MODULE(RCTVoiceAssistant)

#if __has_include(<React/RCTEventEmitter.h>)
/**
 * These methods will be called when the first observer is added and when the
 * last observer is removed (or when dealloc is called), respectively. These
 * should be overridden in your subclass in order to start/stop sending events.
 */
- (void)startObserving
{
    //
}

- (void)stopObserving
{
    //
}

- (NSArray<NSString *> *)supportedEvents{
    return @[
             kEmitResponse,
             ];
}
#endif

- (void)postMessgeNotif:(NSDictionary *)data messageType:(NSString *)type{

#if __has_include(<React/RCTEventEmitter.h>)
    if (self.bridge) {
        [self sendEventWithName:type body:data];
    }
#else
    if (self.bridge) {
        [self.bridge.eventDispatcher sendDeviceEventWithName:type
                                                        body:data];
    }
#endif

}

RCT_EXPORT_METHOD(openVoiceAssistant:(NSDictionary *)options) {
    __weak typeof(self) weakSelf = self;
    __block BOOL shouldPost = NO;
    __block NSDictionary *result = nil;
    [VoiceAssistant openVoiceAssistant:options answer:^BOOL(NSString * _Nonnull answer, NSDictionary *dict) {
        //
        NSLog(@"finish answer:%@", answer);
        NSLog(@"finish dict:%@", dict);
        shouldPost = (dict != nil && dict[@"intent"] != nil && dict[@"intent"][@"semantic"] != nil);
        result = dict;
        //return mDictResult[@"name"] != nil; // 识别到路由跳转(即'scene_'开头)就退出对话界面
        //return NO; // 不自动退出对话，即不执行 finish
        //return YES; // 语音播放完执行 finish
        return shouldPost;
    } finish:^{
        if (shouldPost) {
            [weakSelf postMessgeNotif:result messageType:kEmitResponse];
        }
    }];
}

RCT_EXPORT_METHOD(closeVoiceAssistant) {
    [self.class close];
}

+ (void)close {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    [rootViewController dismissViewControllerAnimated:NO completion:^{
        //
    }];
}

+ (void)closeVoiceAssistant1 {
    if (kShouldFinish) {
        kShouldFinish = NO;
        [self close];
    } else {
        kShouldFinish = YES;
    }
}

@end
